package cn.sunshuai.service.impl;

import cn.sunshuai.domain.Movie;
import cn.sunshuai.domain.MovieUser;
import cn.sunshuai.domain.User;
import cn.sunshuai.exception.BusinessException;
import cn.sunshuai.feignclient.MovieFeignClient;
import cn.sunshuai.mapper.UserMapper;
import cn.sunshuai.service.IUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;

@Service
public class UserServiceImpl implements IUserService {
    @Autowired
    private MovieFeignClient movieFeignClient;

    @Autowired
    private UserMapper userMapper;

    @Override
    public void movieBuy(Long id) {
        Movie movie = movieFeignClient.movieBuy(id);
        if(movie.getStock()<=0){
            throw new BusinessException("没有票了!!");
        }
        movie.setStock(movie.getStock()-1);
        movieFeignClient.addOrUpdateMovie(movie);
        String name = "张三";
        User user = userMapper.loadByUsername(name);
        if(((user.getBalance() - movie.getPrice()) <0)){
            throw new BusinessException("余额不足");
        }
        user.setBalance(user.getBalance()-movie.getPrice());
        userMapper.update(user);
        MovieUser movieUser = new MovieUser();
        movieUser.setMovie_ticket_id(id);
        movieUser.setUser_id(user.getId());
        movieUser.setStatus(0);
        movieFeignClient.addOrUpdate(movieUser);
    }

    @Override
    public void movieSee(Long id) {
        MovieUser movieUser = movieFeignClient.findByMovieId(id);
        if(movieUser.equals(null)){
            throw new BusinessException("你没有该电影票");
        }
        if(movieUser.getStatus()==1){
            throw new BusinessException("该电影票已使用");
        }
        Movie movie = movieFeignClient.movieBuy(id);
        if(movie!=null){
            if((new Date()).compareTo(movie.getEnd_time())>0){
                throw new BusinessException("电影票已过期,不能观看");
            }
        }
    }
}
